﻿CREATE PROCEDURE [dbo].[CashRegisterLinesDelete]
(
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intErrCode int, @intRet int
	SET NOCOUNT ON;

SELECT @intErrCode = Id
FROM CA.GoodsDocLines WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 1, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode

END
	IF EXISTS (SELECT Id FROM CA.GoodsDocLines WHERE ReturnLineId = @Original_Id )
	BEGIN
		SELECT @intErrCode = 2, 
		@strMsg = 'По строке чека с идентификатором ' + cast(@Original_Id as varchar(20)) + ' существуют возвраты! Сперва удалите возвраты.'
		RAISERROR (@strMsg, 11, @intErrCode)
		RETURN @intErrCode
	END

EXEC @intRet = dbo.CheckAllowUpdateDeleteForRecord @Original_Id
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
DELETE FROM [CA].[GoodsDocLines] 
WHERE Id = @Original_Id AND MD = @Original_MD

RETURN 0
